<?php
namespace Model;

class Privilege {
	public function ls($aParam) {
		global $o;
		$aParam ['table'] = 'privileges';
		$aList = $o->Db->ls ( $aParam );
		$aList ['data'] = $this->_formatPrivilege ( $aList ['data'] );
		return $aList;
	}
	
	private function _formatPrivilege($aData) {
		foreach ( $aData as $iKey => $aRow ) {
			$aValue = unserialize ( $aRow ['value'] );
			$aPrivilege = array ();
			if (is_array ( $aValue )) {
				foreach ( $aValue as $sKey => $aVal ) {
					if ($aVal [0] != '__FULL__') {
						foreach ( $aVal as $sVal ) {
							$aPrivilege [] = $sKey . '::' . $sVal;
						}
					} else {
						$aPrivilege [] = $sKey . '::__FULL__';
					}
				}
			}
			$aData [$iKey] ['privilege'] = implode ( ',', $aPrivilege );
		}
		return $aData;
	}
	
	public function add($aInfo) {
		global $o;
		$aInfo ['name'] = trim ( $aInfo ['name'] );
		if ($aInfo ['name'] == '') {
			return false;
		}
		if ($this->_checkExist ( $aInfo ['name'] )) {
			return false;
		}
		$aInfo ['value'] = $this->_getValueByPrivilege ( $aInfo ['privilege'] );
		$aInfo ['auth'] = $aInfo ['auth'] == 'yes' ? 'yes' : 'no';
		return $o->Db->insert ( 'privileges', $aInfo );
	}
	
	public function update($aInfo) {
		global $o;
		$aInfo ['name'] = trim ( $aInfo ['name'] );
		if ($aInfo ['name'] == '') {
			return false;
		}
		$aInfo ['value'] = $this->_getValueByPrivilege ( $aInfo ['privilege'] );
		$aInfo ['auth'] = $aInfo ['auth'] == 'yes' ? 'yes' : 'no';
		$o->Db->update ( 'privileges', $aInfo );
		return true;
	}
	
	private function _checkExist($sName) {
		$aInfo = $this->get ( $sName, 'name' );
		if ($aInfo) {
			return true;
		} else {
			return false;
		}
	}
	
	public function get($iId, $sType = 'id') {
		global $o;
		$aInfo = $o->Db->get ( 'privileges', array (
				$sType => $iId 
		) );
		if ($aInfo) {
			return $aInfo;
		}
		return false;
	}
	
	private function _getValueByPrivilege($sPrivilege) {
		$aPrivilege = explode ( ',', $sPrivilege );
		foreach ( $aPrivilege as $sRow ) {
			list ( $sAction, $sMethod ) = explode ( '::', $sRow );
			if (! $sAction) {
				continue;
			}
			if ($sMethod == '__FULL__') {
				$aValue [$sAction] = array (
						'__FULL__' 
				);
			} else {
				if (is_array ( $aValue [$sAction] ) && $aValue [$sAction] [0] != '__FULL__') {
					$aValue [$sAction] [] = $sMethod;
				} elseif ($aValue [$sAction] [0] != '__FULL__') {
					$aValue [$sAction] [] = $sMethod;
				}
			}
		}
		return serialize ( $aValue );
	}
	
	public function remove($iId) {
		global $o;
		return $o->Db->delete ( 'privileges', $iId );
	}
}

?>